#include <iostream> // for standard I/O
#include <string>   // for strings
#include <time.h>
#include <fstream>
#include <stdio.h>

#include <opencv2/core/core.hpp>        // Basic OpenCV structures (cv::Mat)
#include <opencv2/highgui/highgui.hpp>  // Video write
#include <opencv2/imgproc/imgproc.hpp>

using namespace std;
using namespace cv;

static long frame_num = 0;
static long half_hour = 60*30;

void get_timestamp(char *buffer)
{
	time_t rawtime;
	struct tm * timeinfo;

	time (&rawtime);
	timeinfo = localtime (&rawtime);

	strftime (buffer,80,"%D %r",timeinfo);
}

void update_log()
{
	char buffer[80];
	get_timestamp(buffer);
	cout << "------------------------------------------------\n";
	cout << buffer << endl;
	cout << "------------------------------------------------\n";
	system("./updateLog.sh");
}

void print_greeting()
{
	cout << "*** Starting Cat Recognizer ***" << endl;
	cout << "starting frames from " << frame_num << endl;
}

bool fexists(const char *filename)
{
  ifstream ifile(filename);
  return ifile;
}

void check_images_folder()
{
	char imfile[250];
	do {
		sprintf(imfile,"images/imCurr_%ld.jpg",frame_num);
		if (!fexists(imfile))
			break;
		frame_num++;
	} while(1);
}

int main(int argc, char *argv[])
{	

	check_images_folder();
	print_greeting();
	cout << "frame_num = " << frame_num << endl; 
	int dev_webcam = 0;
	VideoCapture webcam(dev_webcam);
	const string win_catcam = "Cat Cam";
	time_t cur_time, last_time;
	update_log();

	if (webcam.isOpened() == false){
		cout << "Webcam capture unsuccessful" << endl;
		update_log();
		return 0;
	}
	webcam.set(CV_CAP_PROP_FRAME_WIDTH, 120);
	webcam.set(CV_CAP_PROP_FRAME_HEIGHT, 100);

	last_time = time(&last_time);
	// namedWindow(win_catcam);
	Mat last_frame,tmp_frame;
	webcam >> tmp_frame;
	cvtColor(tmp_frame, last_frame, CV_BGR2GRAY);

	do {

		Mat tmp_frame, frame, dif_frame;
		webcam >> tmp_frame;
		cvtColor(tmp_frame, frame, CV_BGR2GRAY);
		// flip(frame,frame,1);
		absdiff(frame, last_frame, dif_frame);		
		Mat mask = dif_frame > 30;
		Scalar fr_mean = mean(mask*255);
		if (fr_mean[0] >=1)
		{
			std::stringstream fname_1,fname_2; 
			fname_1 << "images/imLast_" << frame_num << ".jpg";
			fname_2 << "images/imCurr_" << frame_num << ".jpg";

			string fname_last(fname_1.str());
			string fname_curr(fname_2.str());

			imwrite(fname_last, frame );
			imwrite(fname_curr, last_frame );

			frame_num++;
		}
		// imshow(win_catcam, frame);

		cur_time = time(&cur_time);
		int time_elapsed = cur_time - last_time;
		if (time_elapsed >= half_hour){
			last_time = cur_time;
			system("./addImages2repo.sh");
			update_log();
		}
		last_frame = frame;
		usleep(100000);
	} while (1);
}
